package main

import (
	"log"
	"net/http"
	"time"
	"os"
	"os/signal"
)

func main() {
	//优雅的终止服务ctrl +c == kill -2 pid
	server := &http.Server{
		Addr:         ":8080",
		WriteTimeout: 4 * time.Second,
	}

	quit := make(chan os.Signal)
	//注册通知事件
	signal.Notify(quit, os.Interrupt)

	mux := http.NewServeMux()
	//路由在这写
	mux.Handle("/", &myHandle{})

	mux.HandleFunc("/bye", sayBye)

	server.Handler = mux

	go func() {
		<-quit
		if err := server.Close(); err != nil {
			log.Fatal("Close Server:"+err.Error())

		}
	}()

	log.Println("Starting server...v3")
	//log.Fatal(server.ListenAndServe())
	err := server.ListenAndServe()
	if err != nil {
		if err == http.ErrServerClosed {
			log.Print("Server close under request")
		} else {
			log.Fatal("Server close unexcepted")
		}
	}
	log.Println("Server exit")

}

type myHandle struct {
}

func (*myHandle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello v3,the request URL is :" + r.URL.String()))
}

func sayBye(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Bye bye,this is v3"))
}
